/**
 * 剑指 Offer 05. 替换空格
 * https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/
 */

const codeSpace = ' '.charCodeAt(0);
const codePercent = '%'.charCodeAt(0);
const code2 = '2'.charCodeAt(0);
const code0 = '0'.charCodeAt(0);

/**
 * @param {string} s
 * @return {string}
 */
function replaceSpace(s) {
  let spaceCount = 0;
  for (let i = 0; i < s.length; i += 1) {
    if (s.charCodeAt(i) === codeSpace) {
      spaceCount += 1;
    }
  }
  const length = s.length + spaceCount * 2;
  const result = new Array(length).fill(0);
  let i = 0;
  let j = 0;
  for (; i < length; i += 1, j += 1) {
    const code = s.charCodeAt(j);
    if (code === codeSpace) {
      result[i] = codePercent;
      i += 1;
      result[i] = code2;
      i += 1;
      result[i] = code0;
    } else {
      result[i] = code;
    }
  }
  // eslint-disable-next-line prefer-spread
  return String.fromCharCode.apply(String, result);
}

console.log(replaceSpace('We are happy.') === 'We%20are%20happy.');
